<?php 
namespace App\Models;
use Log,DB;
use App\Cache\BaseCache;
use App\Events\UserSaved;
use Cache;

require_once __DIR__.'/../Library/PhoneMessage/Client.php';

class User extends BaseModel{
	
	//表明
	protected $table = 'user';
	//主键
	protected $primaryKey = 'id';

    protected $LOGIN_TIME_LONG = 3600 * 24 * 30;

    protected $USER_ICONS = array(
        0=>'http://img.ray.onairm.cn/user-portrait-test01.jpg',
        1=>'http://img.ray.onairm.cn/user-portrait-test02.jpg',
        2=>'http://img.ray.onairm.cn/user-portrait-test03.jpg',
        3=>'http://img.ray.onairm.cn/user-portrait-test04.jpg',
        4=>'http://img.ray.onairm.cn/user-portrait-test05.jpg',
        5=>'http://img.ray.onairm.cn/user-portrait-test06.jpg',
    );
    //用户实体信息
    public function getUserObejct($user_id){
        $user =$this->getUserModel($user_id);
        if(isset($user->id) && $user->is_delete != 1){
            $userObject = array(); 
            $userObject['userId'] = $user->id;
            $userObject['token'] = $user->token;//token
            $userObject['nickname'] = $user->nickname;
            $userObject['phone'] = $user->phone;
            $userObject['gender'] = $user->gender;
            $userObject['userIcon'] = $user->icon?$user->icon:$this->USER_ICONS[$user->id%count($this->USER_ICONS)];
            $userObject['organizationObject'] = with(new Organization($this->request))->getOrganizationObejct($user->organization_id);
            $userObject['regdate'] = $user->regdate;
            $userObject['slogan'] = $user->slogan;
            $userObject['keywords'] = $user->keywords;
            $userObject['imgQRCode'] = $user->imgQRCode;
            $userObject['liveTotal'] = $user->liveTotal;//直播总数
            $userObject['fansTotal'] = $user->fansTotal;//粉丝总数
            $userObject['attentionStatus'] = 0;//是否关注
            if($this->request->input('loginStatus') == 1){
                $cache = new BaseCache();
                $cache->method = 'get';
                $cache->cacheName = 'attention';
                $cache->cachePar = array(1,$user->id,$this->request->input('userId')); //集合
                $retcache = $cache->HandleCache();
                if($retcache == 'NO_CACHE'){
                   $status = with(new Attention($this->request))->isAttention(1,$user->id,$this->request->input('userId'));
                   if($status){
                       $userObject['attentionStatus'] = 1;
                   }
                }else if($retcache == 'ATTENTION'){
                    $userObject['attentionStatus'] = 1;
                }
            }    
            $userObject['gold'] = $user->gold;
            return $userObject; 
        }
        return ;
    }
    //获取用户实体
    public function getUserModel($userId){
        $userModelCache = new BaseCache();
        $userModelCache->method = 'get';
        $userModelCache->cacheName = 'userModel';
        $userModelCache->cachePar = array($userId); //集合
        $retCache = $userModelCache->HandleCache();
        if ($retCache !== 'NO_CACHE') {
            if(!isset($retCache->id)){
                return;
            }
            return $retCache;
        }
        if($userId > 0){
            $user = $this->select('id','organization_id','token','token_expires','nickname','phone','icon','regdate','birthday','gender','slogan','keywords','QR_code','live_total','fans_total','gold','is_delete')
                ->where('id','=',$userId)
                ->first();
        } else {
            $user = 'CACHE_BREAKDOWN';
        }
        $userModelCache->method = 'put';
        $userModelCache->cacheValue = $user;
        $userModelCache->HandleCache();
        if(!isset($user->id)){
            return;
        }
        return $user;
    }
    
    public function getUserInfo(){
        $user_id = $this->request->input('uId');
        if($user_id){
            return $this->getUserObejct((int)$user_id);
        }
        return ;
    }
    
    public function getVerifyCode(){
        //获取短信验证码
        $phone = $this->request->input('phone');
        $tn = $this->request->input('tn');
        $dk = $this->request->input('dk');
        $ip = $this->request->ip();
        $auth= with(new ShortMsgRecord($this->request))->sendMsgAuth();
        if(!$auth){
            return ;
        }
        $shortMsg = with(new ShortMsg($this->request))->processPhone();
        if(!$shortMsg){
            return ;
        }
        //事务
        DB::connection(env('MYSQL_CONNECTION','mysql'))->beginTransaction();
        try {
            //发送短信验证码至手机，并且存至数据库一份
            $rand_code = rand(100000, 999999);
            $client = new \Client(env('DUANXIN_GW_URL'),env('DUANXIN_SERIAL_NUMBER'), env('DUANXIN_PASS_WORD'),env('DUANXIN_SESION_KEY'));
            $client->setOutgoingEncoding("UTF-8");
            //发送短信
            $message = '您的验证码为:'.$rand_code;
            $phones = array();
            $phones[0] =$phone;
            $code = $client->sendSMS($phones,$message);
            if($code != 0){
                return false;
            }
            $shortMsg->code = $rand_code;
            $shortMsg->send_at = time();
            $shortMsg->times = 0;
            $shortMsg->save();

            $mg = new ShortMsgRecord($this->request);
            $mg->phone = $phone ;
            $mg->dk = $dk;
            $mg->tn = $tn;
            $mg->remote_addr = $ip;
            $mg->msg = $message;
            $mg->save();            
        } catch (\Exception $exc) {
            DB::connection(env('MYSQL_CONNECTION','mysql'))->rollBack();
            return false;
        }
        DB::connection(env('MYSQL_CONNECTION','mysql'))->commit();
        return TRUE;
    }
    
    public function login(){
        $phone = $this->request->input('phone');
        $ret = with(new ShortMsg($this->request))->compareCode();
        if(!$ret){
            return ;
        }
        //事务
        DB::connection(env('MYSQL_CONNECTION','mysql'))->beginTransaction();
        try {
            $user = $this->select('id','organization_id','token','token_expires','nickname','phone','icon','regdate','birthday','gender','slogan','keywords','QR_code','live_total','fans_total','gold','is_delete')
                    ->where('phone','=',$phone)
                    ->where('is_delete','=',0)
                    ->first();
            if(!$user){
                $user = new User($this->request);
                $user->nickname = '小'.$this->getRandChar(1);
                $icon_num = rand(0, count($this->USER_ICONS));
                $user->icon = $this->USER_ICONS[$icon_num];
                $user->gender = '保密';
                $user->phone = $phone;
                $user->slogan = '锐直播,做你我生活中的直播 ^6^ !';
                $user->regdate = time();
            } 
            //新生成token
            $user->token = str_replace('.', '', uniqid(null, true));   //token 的生成
            $user->token_expires = time() + $this->LOGIN_TIME_LONG; //期限
            $user->save();
        } catch (\Exception $exc) {
            print_r($exc->getMessage());
            DB::connection(env('MYSQL_CONNECTION','mysql'))->rollBack();
            return false;
        }
        DB::connection(env('MYSQL_CONNECTION','mysql'))->commit();
        if(!isset($user->id)){
            return;
        }
        return $this->getUserObejct((int)$user->id);
    }
    
    public function updateUserInfo(){
        $userId = $this->request->input('userId');
        $user = $this->getUserModel($userId);
        if(!isset($user->id)){
            return FALSE;
        }
        $par = $this->request->input();
        $flag = FALSE;
        if(isset($par['nickname']) && $par['nickname']){
            $flag = TRUE;
            $user->nickname = $par['nickname'];
        }
        if(isset($par['slogan']) && $par['slogan']){
            $flag = TRUE;
            $user->slogan = $par['slogan'];
        }
        if(isset($par['birthday']) && $par['birthday']){
            $flag = TRUE;
            $user->birthday = $par['birthday'];
        }
        if(isset($par['icon']) && $par['icon']){
            $flag = TRUE;
            $user->icon = $par['icon'];
        }
        if($flag){
            if(!$user->save()){
              return FALSE;
            }
        }
        return TRUE;
    }
    
    //获取历史记录
    public function getHistoryLog(){
        $userId = $this->request->input('userId');
        $page = $this->request->input('page');
        $size = $this->request->input('size');
        //取缓存
        $liveListCache = new BaseCache();
        $liveListCache->method = 'get';
        $liveListCache->cacheName = 'userHistoryLog';
        $liveListCache->cachePar = array($userId); //集合
        $retliveListCache = $liveListCache->HandleCache();
        if ($retliveListCache === 'NO_CACHE' || ( isset($retliveListCache['more']) && $retliveListCache['more'] == 1 && count($retliveListCache['data']) <= ($info['pageSize'] * ($info['page'] + 1)) )) {
            // 1、不存在缓存 2、有缓存但缓存数量不够且数据库里仍有多个数据
//          判断页码数目
            $skip = 0;
            if ($retliveListCache !== 'NO_CACHE') {
                $skip = $retliveListCache['num'];
            }
            $take_ready = floor(($size * ($page + 1)) / $this->TAKE_NUM) + 1;
            $take = $take_ready - $skip;
            
            $lives = Live::select('live.id', 'live.title', 'live.description', 'live.live_poster', 'live.keywords', 'live.status', 
                    'live.push_stream', 'live.pull_stream', 'live.live_review', 'live.start_time', 'live.visit_total','live.praise_total','live.order_total',
                    'live.set_praise_num','live.set_visit_num','live.anchor_id','live.source_id','live.belong_to','city','live.comment_enable','live.res_id','live.is_delete',
                    'view_history.view_time','view_history.update_time')
                    ->selectRaw('view_history.id as vid')
                    ->where('live.is_delete','=','0')
                    ->where('live.status','!=','4')
                    ->join('view_history', 'view_history.live_id','=','live.id')
                    ->where('view_history.user_id','=',$userId)
                    ->where('view_history.is_delete','=','0')
                    ->orderBy('view_history.update_time', 'desc')
                    ->skip($skip * $this->TAKE_NUM)
                    ->take($take * $this->TAKE_NUM)
                    ->get();
                
            $retLiveListCacheNew = array();
            foreach ($lives as $key => $live) {
                //存缓存-commentModel
                $liveModelCache = new BaseCache();
                $liveModelCache->method = 'put';
                $liveModelCache->cacheName = 'liveModel';
                $liveModelCache->cachePar = array($live->id); //集合
                $liveModelCache->cacheValue = $live;
                $liveModelCache->HandleCache();
                $retLiveListCacheNew['data'][$key]['id'] = $live->id;
                $retLiveListCacheNew['data'][$key]['viewTime'] = $live->view_time;//播放至
                $retLiveListCacheNew['data'][$key]['updateTime'] = $live->update_time;//观看时间
            }
            if (count($lives) < $take * $this->TAKE_NUM) {
                $retLiveListCacheNew['more'] = 0;
            } else {
                $retLiveListCacheNew['more'] = 1;
            }
            $retLiveListCacheNew['num'] = $skip + ceil(count($lives) / $this->TAKE_NUM);
//            Log::info('$retLiveListCacheNew more' . $retLiveListCacheNew['more']);
//            Log::info('$retLiveListCacheNew $ake_ready' . $take_ready);
//            Log::info('$retLiveListCacheNew $num' . $retLiveListCacheNew['num']);
            if ($retliveListCache !== 'NO_CACHE') {
                $retLiveListCacheNew['data'] = array_merge((array) $retliveListCache['data'], (array) $retLiveListCacheNew['data']);
            }
            $retliveListCache =  $retLiveListCacheNew ;
            //存缓存
            $liveListCache = new BaseCache();
            $liveListCache->method = 'put';
            $liveListCache->cacheName = 'userHistoryLog';
            $liveListCache->cachePar = array($userId); //集合
            $liveListCache->cacheValue = $retliveListCache;
            $liveListCache->HandleCache();
        }
        
        //遍历缓存数组 
        $index = $size * $page;
        $liveList = array();
        for ($i = 0; $i < $size; $i++) {
            if (!isset($retliveListCache['data'][$index])) {
                break;
            }
            $liveList[$i]['id'] = $retliveListCache['data'][$index]['id'];
            $liveList[$i]['viewTime'] = $retliveListCache['data'][$index]['viewTime'];
            $liveList[$i]['updateTime'] = $retliveListCache['data'][$index]['updateTime'];
            $index++;
        }
        $data['paging']['size'] = $i;
        
        //判断是否有缓存 实体
        $liveModelCache = new BaseCache();
        $liveModelCache->method = 'has';
        $liveModelCache->cacheName = 'liveModel';
        $index_ids = array();
        foreach ($liveList as $key => $value) {
            if(!isset($value['id'])){
                continue;
            }
            $liveModelCache->cachePar = array($value['id']); //集合
            if ($liveModelCache->HandleCache() === 'NO_CACHE') {
                if (!$value['id']) {
                    continue;
                }
                $index_ids[] = $value['id'];
            }
        }
        if (count($index_ids) > 0) {
            //搜索
            $lives = Live::select('live.id', 'live.title', 'live.description', 'live.live_poster', 'live.keywords', 'live.status', 
                    'live.push_stream', 'live.pull_stream', 'live.live_review', 'live.start_time', 'live.visit_total','live.praise_total','live.order_total',
                    'live.set_praise_num','live.set_visit_num','live.anchor_id','live.source_id','live.belong_to','city','live.comment_enable','live.res_id','live.is_delete')
                    ->whereIn('live.id', $index_ids)
                    ->where('live.is_delete', '=', '0')
                    ->where('live.status', '!=', '4')
                    ->get();
            foreach ($index_ids as $index_id) {
                $live_id = 0;
                foreach ($lives as $key => $live) {
                    if ($index_id == $live->id) {
                        $live_id = $index_id;
                        break;
                    }
                }
                $liveModelCache = new BaseCache();
                $liveModelCache->method = 'put';
                $liveModelCache->cacheName = 'liveModel';
                $liveModelCache->cachePar = array($live_id); //集合
                if ($live_id == 0) {
                    $liveModelCache->cacheValue = 'CACHE_BREAKDOWN';
                } else {
                    $liveModelCache->cacheValue = $live;
                }
                $liveModelCache->HandleCache();
            }
        }
        $data['data'] = array();
        //找出commentObject
        $temp = array();
        foreach ($liveList as $key => $value) {
//            $userId ;
            if(!isset($value['id'])||!isset($value['updateTime'])||!isset($value['viewTime'])){
                continue;
            }
            $temp[$value['id']] = 1;
            $liveModel = with(new Live($this->request))->getLiveObject((int)$value['id']);
            $liveModel['palyTime']=$value['viewTime'];//播放时长
            $liveModel['historyTime']=$value['updateTime'];//历史产生时间
            if ($liveModel) {
                $data['data'][] = $liveModel;
            }
        }
        //获取workman缓存中观看历史纪录数据
        $cacheObject = Cache::get('Raylive_View_History');
        if($cacheObject){
            foreach ($cacheObject['view_list'] as $key=>$val){
                if(array_key_exists($val['live_id'],$temp)){
                    foreach ($data['data'] as $k => $v) {
                        if($v['liveId'] == $val['live_id'] && $userId == $val['user_id'] && $val['update_time']>$v['historyTime']){
                            $t = date('Y-m-d',$val['update_time']);
                            $now = date('Y-m-d',$v['historyTime']);
                            if($now == $t){
                                $data['data'][$k]['historyTime'] = $val['update_time'];
                                $data['data'][$k]['palyTime'] = $val['view_time'];
                                $data_index = $data['data'][$k];
                                unset($data['data'][$k]);
                                array_unshift($data['data'],$data_index);
                            }
                        }
                    }
                }else{
                    //数组插入
                    $liveModel = with(new Live($this->request))->getLiveObject($val['live_id']);
                    $liveModel['palyTime']=$val['update_time'];//播放时长
                    $liveModel['historyTime']=$val['view_time'];//历史产生时间
    //                $data['data'][] = $liveModel;
                    array_unshift($data['data'],$liveModel);
                }
            }
        }
       
         //排序
//        $sortKey = array();
//        foreach ($data['data'] as $val) {
//            $sortKey[] = $val['historyTime'];
//        }
//        array_multisort($sortKey, SORT_DESC, $data['data']);
        return $data;
    }
    
    
    //更新实体
    public function saveModel(){
        $userModelCache = new BaseCache();
        $userModelCache->method = 'forget';
        $userModelCache->cacheName = 'userModel';
        $userModelCache->cachePar = array($this->id); //集合
        $userModelCache->HandleCache();
        if($this->is_delete == 0){
            $this->getUserModel($this->id);
        }
    }
    
    //删除实体
    public function deleteModel(){
        $userModelCache = new BaseCache();
        $userModelCache->method = 'forget';
        $userModelCache->cacheName = 'userModel';
        $userModelCache->cachePar = array($this->id); //集合
        $userModelCache->HandleCache();
    }
    
    //重写
    public function SnycModelHandle(){
        $id = $this->request->input('id');
        $action =  $this->request->input('action');
        $user = new User();
        $user->id = $id;
        if($action == 'delete'){
            $user->deleteModel();
        } else {
            $this->is_delete = 0;
            $user->saveModel();
        }
        
    }
}